package com.zzuli.yxy.task.springDataPipeline;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzuli.yxy.entity.Album;
import com.zzuli.yxy.entity.Singer;
import com.zzuli.yxy.entity.Song;
import lombok.extern.slf4j.Slf4j;
import com.zzuli.yxy.mapper.AlbumMapper;
import com.zzuli.yxy.mapper.SingerMapper;
import com.zzuli.yxy.mapper.SongMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

/**
 * 会获取三种数据
 * song: 歌曲id 、歌曲图片，存入数据库
 * singer: 歌手id、歌手名字，存入数据库，并根据歌曲id、歌手id 更新关联表
 * album：歌单id、歌单名字，存入数据库，并根据歌曲id、歌单id 更新关联表
 * @auther pony
 * @create 2023-04-04 22:35
 */
@Component
public class SingerNamePipeline implements Pipeline {

    @Autowired
    private SongMapper songMapper;

    @Autowired
    private SingerMapper singerMapper;

    @Autowired
    private AlbumMapper albumMapper;

    @Override
    public void process(ResultItems resultItems, Task task) {
        //1、获取 song，存入数据库
        Song songTask = resultItems.get("song");
        System.out.println("最终存入数据库的信息 songTask：" + songTask);
        //添加歌曲图片
        LambdaUpdateWrapper<Song> uw = new LambdaUpdateWrapper<>();
        uw.eq(Song::getSongId, songTask.getSongId());
        uw.set(Song::getSongImg, songTask.getSongImg());
        songMapper.update(songTask, uw);

        //2、获取 album，存入数据库
        Album albumTask = resultItems.get("album");
        System.out.println("最终存入数据库的信息 albumTask：" + albumTask);
        //添加数据
        albumMapper.insert(albumTask);
        //更新歌曲、专辑关联表
        songMapper.addAlbumForSong(songTask.getSongId(), albumTask.getAlbumId());

        //3、获取 singer，存入数据库
        List<Singer> singerTaskList = resultItems.get("singerList");
        System.out.println("最终存入数据库的信息 singerTaskList：" + singerTaskList);
        //数据不为空
        if (singerTaskList!=null||!"".equals(singerTaskList)){
            //添加数据
            for (Singer singer : singerTaskList) {
                singerMapper.insert(singer);
                //更新歌曲、歌手关联表
                songMapper.addSingerForSong(songTask.getSongId(), singer.getSingerId());
            }
        }
    }
}
